package com.mall.mapper;

import com.mall.pojo.CartItem;
import org.apache.ibatis.annotations.*;
import java.util.List;

@Mapper
public interface CartMapper {

    @Insert("""
        INSERT INTO cart (user_id, sku_id, count, checked)
        VALUES (#{userId}, #{skuId}, #{count}, #{selected})
        ON DUPLICATE KEY UPDATE 
            count = count + VALUES(count),
            checked = VALUES(checked),
            update_time = NOW()
    """)
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insert(CartItem item);

    @Select("""
        SELECT c.*, 
               g.name AS goods_name, 
               g.price AS goods_price,
               g.image AS goods_image, 
               g.description AS goods_description,
               u.nickName AS user_nick_name, 
               u.avatar AS user_avatar
        FROM cart c
        JOIN goods g ON c.sku_id = g.id
        JOIN login u ON CAST(c.user_id AS SIGNED) = u.id
        WHERE c.user_id = #{userId}
    """)
    @Results(id = "CartItemResultMap", value = {
            @Result(property = "id", column = "id", id = true),
            @Result(property = "userId", column = "user_id"),
            @Result(property = "skuId", column = "sku_id"),
            @Result(property = "count", column = "count"),
            @Result(property = "price", column = "goods_price"),
            @Result(property = "selected", column = "checked"),
            @Result(property = "createTime", column = "create_time"),
            @Result(property = "updateTime", column = "update_time"),
            @Result(property = "name", column = "goods_name"),
            @Result(property = "picture", column = "goods_image"),
            @Result(property = "goods.name", column = "goods_name"),
            @Result(property = "goods.price", column = "goods_price"),
            @Result(property = "goods.image", column = "goods_image"),
            @Result(property = "goods.description", column = "goods_description"),
            @Result(property = "user.nickName", column = "user_nick_name"),
            @Result(property = "user.avatar", column = "user_avatar")
    })
    List<CartItem> findByUserId(@Param("userId") Long userId);

    @Delete("<script>" +
            "DELETE FROM cart WHERE user_id = #{userId} " +
            "AND id IN <foreach collection='ids' item='id' open='(' separator=',' close=')'>#{id}</foreach>" +
            "</script>")
    void deleteByIds(@Param("userId") Long userId, @Param("ids") List<Long> ids);

    @Select("SELECT * FROM cart WHERE user_id = #{userId} AND sku_id = #{skuId}")
    CartItem findByUserAndGoods(@Param("userId") Long userId, @Param("skuId") Long skuId);

    @Update("""
        UPDATE cart SET 
            count = #{count},
            checked = #{selected},
            update_time = NOW()
        WHERE id = #{id}
    """)
    void update(CartItem existing);
}